import React from 'react'
import PageTitle from 'component/page-title/index.jsx'
import {Link} from 'react-router-dom'
import Pagination from 'until/pagination/index.jsx'
import Muntil from 'until/mm.jsx'
import USer from 'service/user-service.jsx'
import Tablelist from 'until/table-list/index.jsx'

const _mm=new Muntil();
const _user=new USer();

class UserList extends React.Component{
    constructor(){
        super();
        this.state={
            list:[],
            pageNum:1,
        }

    }
    componentDidMount(){
        this.loadUserList();
    }

    loadUserList(){
        _user.getUserList(this.state.pageNum).then(res=>{
            this.setState(res)
        },errMsg=>{
            _mm.errorTips(errMsg)
        });
    }

    //页数变化时,改变pageNum,由于setState是异步函数，再掉用loadUserList
    OnPageNumChange(pageNum){
        this.setState({
            pageNum:pageNum
        },()=>{
            this.loadUserList()
        })
    }

    render(){

        let tableHeads=[
            {name:'ID',width:'10%'},
            {name:'用户名',width:'20%'},
            {name:'邮箱',width:'20%'},
            {name:'电话',width:'20%'},
            {name:'注册时间',width:'30%'},
        ]

        let listBody= this.state.list.map((user,index)=>{
            return (
                <tr key={index}>
                    <th>{user.id}</th>
                    <th>{user.username}</th>
                    <th>{user.email}</th>
                    <th>{user.phone}</th>
                    <th>{new Date(user.createTime).toLocaleString()}</th>
                </tr>
            )
        })

        return(
            <div id="page-wrapper">
                <PageTitle title="用户列表"/>

                <Tablelist tableHeads={tableHeads}>
                    {listBody}
                </Tablelist>
                <Pagination current={this.state.pageNum}
                            total={this.state.total}
                            onChange={(pageNum)=>{this.OnPageNumChange(pageNum)}}/>

            </div>
        )
    }

}

export default UserList;